<template>
  <div class="virtual-table" style="margin: 20px;"  >
    <el-table  ref="tableBody" :data="visibleRows" border @scroll="handleScroll" :height="state.tableHeight">
      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column label="name" prop="name"></el-table-column>
      <el-table-column label="age" prop="age"></el-table-column>
      <el-table-column label="email" prop="email"></el-table-column>
    </el-table>
    <div class="placeholder" :style="{ height: placeholderHeight + 'px' }"></div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted ,reactive} from 'vue';

const state = reactive({
  tableHeight:400
})

// 模拟数据
const rows = ref(Array.from({ length: 1000 }, (_, index) => ({
  id: index,
  name: `Name ${index}`,
  age: Math.floor(Math.random() * 100),
  email: `email${index}@example.com`
})));

const columns = ref([
  { key: 'id', label: 'ID' },
  { key: 'name', label: 'Name' },
  { key: 'age', label: 'Age' },
  { key: 'email', label: 'Email' }
]);

const tableBody = ref(null);
const rowHeight = 30;

// 计算可见区域的起始和结束索引
const visibleStartIndex = computed(() => {
  if (!tableBody.value) return 0;
  return Math.floor(tableBody.value.scrollTop / rowHeight);
});

const visibleEndIndex = computed(() => {
  const visibleRowsCount = Math.ceil(state.tableHeight / rowHeight);
  console.log("🚀 ~ visibleEndIndex ~ visibleRowsCount:", visibleRowsCount)
  return visibleStartIndex.value + visibleRowsCount;
});

// 计算可见的数据行
const visibleRows = computed(() => {
  return rows.value.slice(visibleStartIndex.value, visibleEndIndex.value);
});

// 计算占位符的高度
const placeholderHeight = computed(() => {
  return rows.value.length * rowHeight;
});

const handleScroll = () => {
  // 滚动时重新计算可见区域
  const buffer = 5; 
  const newStartIndex = Math.max(0, visibleStartIndex.value - buffer);
  const newEndIndex = Math.min(rows.value.length, visibleEndIndex.value + buffer);
};

onMounted(() => {
  // 初始化时设置占位符高度
});
</script>

<style scoped>
.virtual-table {
  position: relative;
  height: 400px;
  overflow-y: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th,
td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

.placeholder {
  position: absolute;
  top: 0;
  left: 0;
  width: 1px;
  z-index: -1;
}
</style>    